/*
 * Copyright (C) 2012, 2013 by Ralph Germ, Martin Budden, Arne Kesting, Martin Treiber
 * <ralph.germ@gmail.com>
 * Copyright (C) 2013 by Osama Abdelkhaleq, Andrew Foxworth, Jasmine Griffiths, Kyle Kenik
 * -----------------------------------------------------------------------------------------
 * 
 * This file is part of
 * 
 * MovSimDroid.
 * 
 * MovSimDroid is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * MovSimDroid is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with MovSim. If not, see <http://www.gnu.org/licenses/>
 * or <http://www.movsim.org>.
 * 
 * -----------------------------------------------------------------------------------------
 */
package org.movsim.movdroid;

import org.movsim.input.ProjectMetaData;
import org.movsim.simulator.SimulationRunnable;
import org.movsim.simulator.Simulator;
import org.movsim.simulator.roadnetwork.RoadNetwork;
import org.movsim.simulator.roadnetwork.RoadSegment;
import org.movsim.simulator.roadnetwork.TrafficLight;
import org.movsim.simulator.roadnetwork.VariableMessageSignBase;

import android.app.ActionBar;
import android.content.Context;
import android.content.res.Resources;
import android.view.Menu;
import android.view.MenuItem;

/*
 * Description: Contains specifications for the Action Bar shown when the user touches the
 * 		start button on application launch.
 * 
 * Known Bugs: None!
 */
public class MovSimActionBar {
	private Resources res;
	private ActionBar actionBar;
	private Simulator simulator;
	private RoadNetwork roadNetwork;
	private SimulationRunnable simulationRunnable;
	private ProjectMetaData projectMetaData;
	private boolean diversionOn = false;
	private MovSimDroidActivity movSimDroidActivity;
	private boolean ifConfiged = false;

	public MovSimActionBar(MovSimDroidActivity movSimDroidActivity,
			Simulator simulator) {
		this.movSimDroidActivity = movSimDroidActivity;
		this.simulator = simulator;
		res = movSimDroidActivity.getResources();
		roadNetwork = simulator.getRoadNetwork();
		simulationRunnable = simulator.getSimulationRunnable();
		projectMetaData = ProjectMetaData.getInstance();

		initActionBar(movSimDroidActivity);
	}

	/* Initialize action bar with theme from Main Activity */
	private void initActionBar(MovSimDroidActivity movSimDroidActivity) {
		actionBar = movSimDroidActivity.getActionBar();
		actionBar.setBackgroundDrawable(res
				.getDrawable(R.drawable.abs__ab_transparent_dark_holo));

	}

	/* Start event handlers for action bar components on touch */
	public void selectAction(MenuItem item) {
		final CharSequence title = item.getTitle();
		if (title.equals(res.getString(R.string.start))) {
			actionStart(item);
		} else if (title.equals(res.getString(R.string.pause))) {
			actonPause(item);
		} else if (title.equals(res.getString(R.string.restart))) {
			actionRestart();
			// } else if (title.equals(res.getString(R.string.faster))) {
			// actionFaster();
			// } else if (title.equals(res.getString(R.string.slower))) {
			// actionSlower();
		} else if (title.equals(res.getString(R.string.info))) {
			actionScenarioInfo(movSimDroidActivity.getNavigationItemPosition());
		} else if (title.equals(res.getString(R.string.movsimInfo))) {
			actionInfo();
		} else if (title.equals(res.getString(R.string.action))) {
			// calls method to start configuration of traffic lights activity if
			// scenario is "intersection on one of the levels"
			if (projectMetaData.getProjectName().equals("intersection")
					|| projectMetaData.getProjectName().equals("level1")
					|| projectMetaData.getProjectName().equals("level2")
					|| projectMetaData.getProjectName().equals("level3")) {
				movSimDroidActivity.startConfig();
				ifConfiged = true;
			} else {
				actionInteraction();
			}
		}
	}

	/* Draw currently selected level */
	private void actionInteraction() {
		movSimDroidActivity.runOnUiThread(new Runnable() {

			@Override
			public void run() {
				for (RoadSegment roadSegment : roadNetwork) {
					if (projectMetaData.getProjectName().equals("routing")) {
						if (roadNetwork.hasVariableMessageSign()
								&& roadSegment.userId().equals("1")) {
							VariableMessageSignBase variableMessageSign = movSimDroidActivity
									.getVariableMessageSign();
							if (diversionOn == false) {
								diversionOn = true;
								roadSegment
										.addVariableMessageSign(variableMessageSign);
							} else {
								diversionOn = false;
								roadSegment
										.removeVariableMessageSign(variableMessageSign);
							}
						}
					}
					if (roadSegment.trafficLights() != null) {
						for (final TrafficLight trafficLight : roadSegment
								.trafficLights()) {
							trafficLight.nextState();
							movSimDroidActivity.getMovSimTrafficView()
									.forceRepaintBackground();
						}
					}
				}
			}
		});

	}

	// private void actionSlower() {
	// int sleepTime = simulationRunnable.sleepTime();
	// sleepTime += sleepTime < 5 ? 1 : 5;
	// if (sleepTime > 500) {
	// sleepTime = 500;
	// }
	// simulationRunnable.setSleepTime(sleepTime);
	// }
	//
	// private void actionFaster() {
	// int sleepTime = simulationRunnable.sleepTime();
	// sleepTime -= sleepTime <= 5 ? 1 : 5;
	// if (sleepTime < 0) {
	// sleepTime = 0;
	// }
	// simulationRunnable.setSleepTime(sleepTime);
	// }

	/* Stop current simulation, clear data, and restart simulation. */
	private void actionRestart() {
		simulationRunnable.pause();
		movSimDroidActivity.createInputStreams();
		roadNetwork.clear();
		simulator.initialize();
		simulationRunnable.start();
		simulationRunnable.pause();
		movSimDroidActivity.getMovSimTrafficView().forceRepaintBackground();
		movSimDroidActivity.getMovSimTrafficView().triggerLightChange(); // used
																			// to
																			// reset
																			// traffic
																			// light
																			// trigger
		reset();
	}

	/* Reset current simulation. */
	void reset() {
		ifConfiged = false;
		diversionOn = false;
		movSimDroidActivity.getMenu().getItem(0)
				.setIcon(R.drawable.ic_action_start).setTitle(R.string.start);
		movSimDroidActivity.getMenu().getItem(2).setEnabled(true);
	}

	/* Show intro text window when selected */
	private void actionInfo() {
		String infoText = res.getString(R.string.introduction_text);
		movSimDroidActivity.showInfo(infoText);
	}

	/* More instructions */
	private void actionScenarioInfo(int projectPosition) {
		String infoText = res.getStringArray(R.array.infoScenario)[projectPosition];
		movSimDroidActivity.showInfo(infoText);
	}

	/* Pause event */
	private void actonPause(MenuItem item) {
		item.setIcon(R.drawable.ic_action_start);
		item.setTitle(R.string.start);
		simulationRunnable.pause();
	}

	/* Start simulation */
	private void actionStart(MenuItem item) {
		if (ifConfiged == false) {
			movSimDroidActivity.startConfig();
			ifConfiged = true;
		} // launch config screen
		movSimDroidActivity.getMenu().getItem(2).setEnabled(false);
		item.setIcon(R.drawable.ic_action_pause);
		item.setTitle(R.string.pause);
		if (!simulationRunnable.isPaused()) {
			simulationRunnable.start();

		} else {
			simulationRunnable.resume();
		}
	}

}
